package com.pdd.zookeeper.web;

import com.alibaba.fastjson.JSON;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author:liyangpeng
 * @date:2020/8/27 10:33
 */
@RestController
@RequestMapping("/zookeeper")
public class ZookeeperController {

    @Autowired
    private ZooKeeper zooKeeper;

    @GetMapping("/getNode")
    public String addNode(String path) throws KeeperException, InterruptedException {
        zooKeeper.getData("/pdd", new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if(watchedEvent.getType()== Event.EventType.NodeDataChanged){
                    System.out.println("pdd的数据发生被修改了");
                }
            }
        },null);

        Stat exists = zooKeeper.exists(path, false);
        if(exists==null){
            zooKeeper.create(path,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
        }
        return null;
    }

    @GetMapping("/delNode")
    public String delNode(String path) throws KeeperException, InterruptedException {
        zooKeeper.delete(path,0);
        return null;
    }
}
